<template>
  <div class="layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="备件出库记录" name="1">
          <TableSearch
            :search="state.search"
            @search="onSearch"
            @listenClick="listenClick"
          />
          <Table
            ref="tableRef"
            v-bind="state.tableData"
            class="table-demo"
            @pageChange="onTablePageChange"
            @listenClick="listenClick"
            @dataList="dataList1"
          >
          </Table>
        </el-tab-pane>
        <el-tab-pane label="备件入库记录" name="2">
          <TableSearch
            :search="state.search2"
            @search="onSearch2"
            @listenClick="listenClick2"
          />
          <Table
            ref="tableRef"
            v-bind="state.tableData2"
            class="table-demo"
            @pageChange="onTablePageChange2"
            @listenClick="listenClick2"
            @dataList="dataList2"
          >
          </Table>
        </el-tab-pane>
      </el-tabs>
      <InOutDialog
        :dialogVisible="dialogVisible"
        :dialogForm="dialogForm"
        @closeDetail="closeDetail"
      ></InOutDialog>
      <TaskWBDetail
        :dialogVisible="wbVisible"
        :dialogForm="wbForm"
        @closeDetail="closeWBDetail"
      ></TaskWBDetail>
      <TaskDJDetail
        :dialogVisible="djVisible"
        :dialogForm="djForm"
        @closeDetail="closeDJDetail"
      ></TaskDJDetail>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted, defineAsyncComponent } from 'vue'
import { ElMessage, TabsPaneContext } from 'element-plus'
import {
  getOutInfoApi,
  getInInfoApi,
  derivedRecordApi,
  derivedRecordInApi
} from '/@/api/spare'
import { dictionaryList } from '/@/api/publicApi'
import router from '/@/router'
import { useRoute } from 'vue-router'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { getWBTaskInfoApi } from '/@/api/maintain'
import { getDJTaskInfoApi } from '/@/api/check'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const route = useRoute()
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const InOutDialog = defineAsyncComponent(
  () => import('./components/InOutDialog.vue')
)
const TaskWBDetail = defineAsyncComponent(
  () => import('../maintenance/components/TaskDetail.vue')
)
const TaskDJDetail = defineAsyncComponent(
  () => import('../check/components/TaskDetail.vue')
)
const activeName = ref(route.query.active ? route.query.active : '1')
const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = ref({
  form: {},
  title: ''
})

// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'retrievalType', colWidth: '', title: '出库类型', type: 'text' },
      { key: 'totalAmount', colWidth: '', title: '出库备件数量', type: 'text' },
      {
        key: 'totalMoney',
        colWidth: '',
        title: '备件总价值(元)',
        type: 'text'
      },
      { key: 'applyUserName', colWidth: '', title: '申请人', type: 'text' },
      { key: 'createUserName', colWidth: '', title: '出库人', type: 'text' },
      { key: 'createTime', colWidth: '', title: '出库时间', type: 'text' },
      { key: 'orderNum', colWidth: '', title: '关联单号', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'outDetails',
        text: '出库详情',
        type: 'primary',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'ckDetailBtn'
      },
      {
        name: 'outNumberDetails',
        text: '单号详情',
        type: 'primary',
        hide(row: any): boolean {
          return row.orderNum != ''
        },
        btns: buttonCodes.value,
        btnCode: 'ckNumberDetailBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRetrieval/pageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false, // 是否可以扩展
      operateWidth: '250', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {
      type: 1 // 必传参数，分页的不要传
    }
  },
  tableData2: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'warehouseType', colWidth: '', title: '入库类型', type: 'text' },
      { key: 'totalAmount', colWidth: '', title: '入库备件数量', type: 'text' },
      {
        key: 'totalMoney',
        colWidth: '',
        title: '备件总价值(元)',
        type: 'text'
      },
      { key: 'applyUserName', colWidth: '', title: '申请人', type: 'text' },
      { key: 'createUserName', colWidth: '', title: '入库人', type: 'text' },
      { key: 'createTime', colWidth: '', title: '入库时间', type: 'text' },
      { key: 'refundNum', colWidth: '', title: '关联退还单号', type: 'text' },
      { key: 'orderNum', colWidth: '', title: '关联单号', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'inDetails',
        text: '入库详情',
        type: 'primary',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'rkDetailBtn'
      },
      {
        name: 'inNumberDetails',
        text: '单号详情',
        type: 'primary',
        hide(row: any): boolean {
          return row.orderNum != ''
        },
        btns: buttonCodes.value,
        btnCode: 'rkNumberDetailBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartWarehouse/pageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false, // 是否可以扩展
      operateWidth: '250', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {
      type: 1 // 必传参数，分页的不要传
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入人名/工单号搜索',
        type: 'input'
      },
      {
        label: '时间筛选',
        prop: 'daterange',
        placeholder: '选择时间',
        type: 'daterange'
      },
      {
        label: '出库类型',
        prop: 'retrievalType',
        placeholder: '出库类型',
        options: [],
        type: 'select2'
      }
    ],
    btn: [
      {
        text: '导出记录',
        fun: 'outboundExport',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'ckExportRecordBtn'
      }
    ],
    reset: true
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search2: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入人名/退还单号/工单号搜索',
        type: 'input'
      },
      {
        label: '时间筛选',
        prop: 'daterange',
        placeholder: '选择时间',
        type: 'daterange'
      },
      {
        label: '入库类型',
        prop: 'warehouseType',
        placeholder: '入库类型',
        options: [],
        type: 'select2'
      }
    ],
    btn: [
      {
        text: '导出记录',
        fun: 'warehousingExport',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'rkExportRecordBtn'
      }
    ],
    reset: true
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}

const list1 = ref([])
const dataList1 = (val: any) => {
  list1.value = val.records
}

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  if (
    state.tableData.param.daterange &&
    state.tableData.param.daterange.length != 0
  ) {
    state.tableData.param.startTime = state.tableData.param.daterange[0]
    state.tableData.param.endTime = state.tableData.param.daterange[1]
  } else {
    state.tableData.param.startTime = ''
    state.tableData.param.endTime = ''
  }
  if (state.tableData.param.retrievalType == '全部') {
    state.tableData.param.retrievalType = ''
  }
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}
// 初始化列表数据
const getTableData2 = () => {
  state.tableData2.flash = !state.tableData2.flash
}

const list2 = ref([])
const dataList2 = (val: any) => {
  list2.value = val.records
}

// 搜索点击时表单回调
const onSearch2 = (data: EmptyObjectType) => {
  state.tableData2.param = Object.assign({}, state.tableData2.param, {
    ...data
  })
  if (
    state.tableData2.param.daterange &&
    state.tableData2.param.daterange.length != 0
  ) {
    state.tableData2.param.startTime = state.tableData2.param.daterange[0]
    state.tableData2.param.endTime = state.tableData2.param.daterange[1]
  } else {
    state.tableData2.param.startTime = ''
    state.tableData2.param.endTime = ''
  }
  if (state.tableData2.param.warehouseType == '全部') {
    state.tableData2.param.warehouseType = ''
  }
  state.tableData2.flash = !state.tableData2.flash
}
// 分页改变时回调
const onTablePageChange2 = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData2()
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event);
}

const getRetrievalType = () => {
  let params = { configType: 'retrieval_type', keyword: '' }
  dictionaryList(params).then((res) => {
    if (res.code == 0) {
      state.search.param.forEach((i: any) => {
        if (i.prop == 'retrievalType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}
const getWarehouseType = () => {
  let params = { configType: 'warehouse_type', keyword: '' }
  dictionaryList(params).then((res) => {
    if (res.code == 0) {
      state.search2.param.forEach((i: any) => {
        if (i.prop == 'warehouseType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}

const outDetails = (row: any) => {
  getOutInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      dialogForm.value.form = res.data
      dialogForm.value.title = '出库'
      dialogVisible.value = !dialogVisible.value
    }
  })
}
const inDetails = (row: any) => {
  getInInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      dialogForm.value.form = res.data
      dialogForm.value.title = '入库'
      dialogVisible.value = !dialogVisible.value
    }
  })
}

const closeDetail = () => {
  dialogForm.value.form = {}
  dialogForm.value.title = ''
  dialogVisible.value = !dialogVisible.value
}

let timer: any = null
const outboundExport = () => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    let params = {
      retrievalType: state.tableData.param.retrievalType
        ? state.tableData.param.retrievalType
        : '',
      keword: state.tableData.param.keyword
        ? state.tableData.param.keyword
        : '',
      startTime: state.tableData.param.startTime
        ? state.tableData.param.startTime
        : '',
      endTime: state.tableData.param.endTime
        ? state.tableData.param.endTime
        : ''
    }
    if (list1.value.length == 0) {
      ElMessage.warning('暂无数据可导出')
    } else {
      derivedRecordApi(params).then((res: any) => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.download = '设备备件出库记录.xls'
        link.href = url
        link.click()
        URL.revokeObjectURL(url) // 释放内存
      })
    }
  }, 1000)
}

let timer2: any = null
const warehousingExport = () => {
  timer2 && clearTimeout(timer2)
  timer2 = setTimeout(() => {
    let params = {
      warehouseType: state.tableData2.param.warehouseType
        ? state.tableData2.param.warehouseType
        : '',
      keword: state.tableData2.param.keyword
        ? state.tableData2.param.keyword
        : '',
      startTime: state.tableData2.param.startTime
        ? state.tableData2.param.startTime
        : '',
      endTime: state.tableData2.param.endTime
        ? state.tableData2.param.endTime
        : ''
    }
    if (list2.value.length == 0) {
      ElMessage.warning('暂无数据可导出')
    } else {
      derivedRecordInApi(params).then((res: any) => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.download = '设备备件入库记录.xls'
        link.href = url
        link.click()
        URL.revokeObjectURL(url) // 释放内存
      })
    }
  }, 1000)
}

const wbVisible = ref<boolean>(false) //弹窗是否出现
const wbForm = ref<any>({
  title: '',
  form: <any>{},
  type: '',
  code: 1
})
const djVisible = ref<boolean>(false) //弹窗是否出现
const djForm = ref<any>({
  title: '',
  form: <any>{},
  type: '',
  code: 1
})
const outNumberDetails = (row: any) => {
  if (row.retrievalType == '维保出库') {
    getWBTaskInfoApi(row.orderNum).then((res) => {
      if (res.code == 0) {
        wbForm.value.form = res.data
        wbForm.value.title = res.data.taskOrderNum
        wbForm.value.type = '1'
        wbVisible.value = !wbVisible.value
      }
    })
  } else if (row.retrievalType == '点检出库') {
    getDJTaskInfoApi(row.orderNum).then((res) => {
      if (res.code == 0) {
        djForm.value.form = res.data
        djForm.value.title = res.data.taskOrderNum
        djForm.value.type = '1'
        djVisible.value = !djVisible.value
      }
    })
  } else {
    router.push({
      name: 'repairOrderDetail',
      query: {
        id: row.orderNum,
        type: 'record',
        from: 1
      }
    })
  }
}

const closeWBDetail = () => {
  wbVisible.value = !wbVisible.value
}
const closeDJDetail = () => {
  djVisible.value = !djVisible.value
}

const inNumberDetails = (row: any) => {
  if (row.warehouseType == '维保退还入库') {
    getWBTaskInfoApi(row.orderNum).then((res) => {
      if (res.code == 0) {
        wbForm.value.form = res.data
        wbForm.value.title = res.data.taskOrderNum
        wbForm.value.type = '1'
        wbVisible.value = !wbVisible.value
      }
    })
  } else if (row.warehouseType == '点检退还入库') {
    getDJTaskInfoApi(row.orderNum).then((res) => {
      if (res.code == 0) {
        djForm.value.form = res.data
        djForm.value.title = res.data.taskOrderNum
        djForm.value.type = '1'
        djVisible.value = !djVisible.value
      }
    })
  } else {
    router.push({
      name: 'repairOrderDetail',
      query: {
        id: row.orderNum,
        type: 'record',
        from: 2
      }
    })
  }
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  outDetails: outDetails,
  outboundExport: outboundExport,
  outNumberDetails: outNumberDetails
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun2 = {
  inDetails: inDetails,
  warehousingExport: warehousingExport,
  inNumberDetails: inNumberDetails
}
// 监听子级表格  传过来的方法
const listenClick2 = (name: string, val: any) => {
  objFun2[name](val)
}

// 页面加载时
onMounted(() => {
  getTableData()
  getRetrievalType()
  getWarehouseType()
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/spare/recordList') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss"></style>
